package com.android.geotrack;

import java.io.IOException;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.ZoomControls;
import android.widget.AdapterView.OnItemSelectedListener;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class LocationActivity extends MapActivity// implements LocationListener
{
	private LinearLayout linearLayout;
	private MapView mapView;
	private ZoomControls mZoom;
	private List<Overlay> mapOverlays;
	private Drawable drawable;
	private HelloItemizedOverlay itemizedOverlay;
	private MapController mc;
	private Geocoder gc;
	
	public String country;
	
	private Spinner countrySpinner;
	private String newCountry;
	
	private LocationManager locMan;
	private Location curLocation;
	private volatile double latitude;
	private volatile double longitude;

	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location_tab);
    	
    	// manual country selection
    	countrySpinner = (Spinner) findViewById(R.id.countrySpinner);
    	
    	ArrayAdapter adapter = ArrayAdapter.createFromResource(this, 
    			R.array.countries, android.R.layout.simple_spinner_item);
 	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 	    countrySpinner.setAdapter(adapter); 
    	
    	countrySpinner.setOnItemSelectedListener(countryListener);
		
		// init map controls
        gc = new Geocoder(this);
        linearLayout = (LinearLayout) findViewById(R.id.zoomview);
    	mapView = (MapView) findViewById(R.id.mapview);
        mc = mapView.getController();
    	mZoom = (ZoomControls) mapView.getZoomControls();
    	linearLayout.addView(mZoom);
    	mapOverlays = mapView.getOverlays();
    	
    	// set location
		//setCurrentGpsLocation(null);
    	locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, gpsListener);  
    	
    	drawable = this.getResources().getDrawable(R.drawable.marker);
    	HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
    	
    	//mapOverlays.clear();
    	GeoPoint point1 = new GeoPoint((int)(latitude),(int) (longitude));
    	OverlayItem overlayitem1 = new OverlayItem(point1, "Bram", "T");
    	itemizedoverlay.addOverlay(overlayitem1);
    	mapView.computeScroll();
    	mapView.clearFocus();
    	mapOverlays.add(itemizedoverlay);
    	
    	// exit button
    	final Button buttonExit = (Button) findViewById(R.id.exitButton);
    	buttonExit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {            	
            	finish();
            }
        });
	}

	private OnItemSelectedListener countryListener = new OnItemSelectedListener()
	{
        public void onItemSelected(AdapterView parent, View v, int position, long id)
        {
        	TopTracksActivity.country = ((String) countrySpinner.getSelectedItem()).toLowerCase();
        	gotoSelected();
        }
        public void onNothingSelected(AdapterView arg0) {}
    };
    
    private void selectLocation(String country)
    {
    	for(int c=0; c<countrySpinner.getCount(); c++)
    		if(countrySpinner.getItemAtPosition(c).equals(country)) {
    	    	countrySpinner.setSelection(c, true);
    	    	return;
    		}
    }
    
    public void gotoSelected()
    {
		newCountry = (String) countrySpinner.getSelectedItem();
		int pos = countrySpinner.getSelectedItemPosition();
		
		try {
		
			// Search addresses
			List<Address> foundAdresses = gc.getFromLocationName(newCountry, 5); 
			                          
			if (foundAdresses.size() == 0) { //if no address found, display an error 
				
				Dialog locationError = new AlertDialog.Builder(LocationActivity.this)
					.setIcon(0).setTitle("Error") .setPositiveButton(R.string.hello, null)
					.setMessage("Sorry, your address doesn't exist.").create(); 
				locationError.show(); 
				
			} else { //else display address on map 
				
				latitude = foundAdresses.get(0).getLatitude() * 1000000;
				longitude = foundAdresses.get(0).getLongitude() * 1000000;
				navigateToLocation(latitude, longitude, mapView);
			
			} 
	
		} catch (Exception e) { 
			//@todo: Show error message 
		}
	} 
    
	@Override
	protected boolean isRouteDisplayed()
	{
		return false;
	}
	
	/** 
	 * Navigates a given MapView to the specified Longitude and Latitude 
	 */ 
	public void navigateToLocation(double latitude, double longitude, MapView mv)
	{  
		GeoPoint p = new GeoPoint((int) latitude, (int) longitude); //new GeoPoint 
		mv.displayZoomControls(true); //display Zoom (seems that it doesn't work yet) 
		MapController mc = mv.getController(); 
		mc.animateTo(p); //move map to the given point 
		//int zoomlevel = mv.getMaxZoomLevel(); //detect maximum zoom level 
		//mc.setZoom(zoomlevel - 13); //zoom 
		mv.setSatellite(false); //display only "normal" mapview
		
		placeMarker();
		
        Log.v("Location", "Location set to " + latitude + ", " + longitude + "!");
	}
	
	/**
	 * Places marker at current location.
	 */
	public void placeMarker()
	{
		mapOverlays.clear();
		drawable = this.getResources().getDrawable(R.drawable.marker);
		HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
		GeoPoint point = new GeoPoint((int)(latitude),(int) (longitude));
		OverlayItem overlayitem = new OverlayItem(point, "Foobar", "T");
		itemizedoverlay.addOverlay(overlayitem);
		
		mapView.computeScroll();
		mapView.clearFocus();
		mapOverlays.add(itemizedoverlay);
	}
	
	private LocationListener gpsListener = new LocationListener()
		{
			boolean locationChanged = false; 
			public void onLocationChanged(Location location)
			{
				curLocation = location;
				     
				latitude = curLocation.getLatitude() * 1000000;
				longitude = curLocation.getLongitude() * 1000000;
				
				navigateToLocation(latitude, longitude, mapView);
				
				try {
					List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
					if(addresses!=null && addresses.get(0) != null)
						selectLocation(addresses.get(0).getCountryName());
				} catch (IOException e) {
					Log.e("Exception", e.toString());
				}
			}
			public void onProviderDisabled(String provider){}
			public void onProviderEnabled(String provider){}
			public void onStatusChanged(String provider, int status, Bundle extras){}
		};
	
}